import { fileURLToPath } from "url";
import { loadEnv, defineConfig } from "vite";

import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import vueDevTools from "vite-plugin-vue-devtools";

import unocss from "unocss/vite";
import autoImport from "unplugin-auto-import/vite";
import components from "unplugin-vue-components/vite";
import { NaiveUiResolver } from "unplugin-vue-components/resolvers";

import { dirs, imports, resolver } from "./auto-import";

export default defineConfig((env) => {
  const { VITE_BASE_PATH, VITE_CONSOLE, VITE_DEBUGGER } = loadEnv(
    env.mode,
    process.cwd()
  );
  return {
    base: VITE_BASE_PATH,
    css: {
      preprocessorOptions: {
        scss: {
          api: "modern-compiler",
          additionalData: '@use "@/styles/mixins.scss" as *;',
        },
      },
    },
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    server: {
      port: 8080,
      cors: true,
      host: true,
      open: false,
      proxy: {
        "/api": {
          target: "http://localhost:3000",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
    build: {
      target: "modules",
      sourcemap: false,
      cssCodeSplit: true,
      assetsInlineLimitL: 4096,
      chunkSizeWarningLimit: 4096,
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: VITE_CONSOLE === "true",
          drop_debugger: VITE_DEBUGGER === "true",
        },
      },
    },
    optimizeDeps: {
      include: ["lodash-es", "@vueuse/core"],
    },
    plugins: [
      vue(),
      vueJsx(),
      vueDevTools(),
      unocss({
        configFile: "./unocss.config.ts",
      }),
      autoImport({
        imports: [imports, "vue", "vue-router", "pinia", "@vueuse/core"],
      }),
      components({
        dirs: dirs,
        deep: false,
        resolvers: [resolver, NaiveUiResolver()],
      }),
    ],
  };
});
